package com.androidhive.androidlistview;

	import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

	public class LoginActivity extends Activity {
		int CID,VID,BIDCOST,QNT;
		String pkgcost=new String();
		String pcost=new String();
		String VendorId=new String();
		String CropId=new String();
		Spinner pkgCost;
		String nu,msg="";
		 public final static String EXTRA_MESSAGE1 = " ";
		 public final static String EXTRA_MESSAGE2 = " ";
		 public final static String EXTRA_MESSAGE3 = " ";
		 public final static String EXTRA_MESSAGE4 = " ";
		
		
		// Email, password edittext
		EditText txtUsername, txtPassword;
		  DatabaseHandler db = new DatabaseHandler(this);
		// login button
		Button btnLogin;
		
		// Alert Dialog Manager
		AlertDialogManager alert = new AlertDialogManager();
		
		// Session Manager Class
		SessionManager session;

	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_login); 
	        
	        // Session Manager
	        session = new SessionManager(getApplicationContext());                
	        
	        // Email, Password input text
	    	pkgCost = (Spinner) findViewById(R.id.spinner1);
	    	List<String> list = new ArrayList<String>();
	    	 Intent intent = getIntent();
			    String CropIdnew = intent.getStringExtra(MyWebViewClient.cropId);
	    	 session.createLoginSessionCropId(CropIdnew);
		    HashMap<String, String> user = session.getUserDetails();
		      
		         VendorId = (user.get(SessionManager.Vendor_Id)); 
		         CropId = user.get(SessionManager.Crop_Id);
		         pkgcost=db.getpkgCost(Integer.parseInt(CropId));
		         
		         list.add("Yes("+pkgcost+" Rs/Ton)");
		         list.add("No");
		         ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
		 		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 		pkgCost.setAdapter(dataAdapter);
		         
		         
	        txtUsername = (EditText) findViewById(R.id.txtUsername);
	        txtPassword = (EditText) findViewById(R.id.txtPassword); 
	        
	      //  Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
	        
	        
	        // Login button
	        btnLogin = (Button) findViewById(R.id.btnLogin);
	        
	        
	        // Login button click event
	        btnLogin.setOnClickListener(new View.OnClickListener() {
				
				//@Override
				public void onClick(View arg0) {
					// Get username, password from EditText
					String username = txtUsername.getText().toString();
					String password = txtPassword.getText().toString();
					pcost=String.valueOf(pkgCost.getSelectedItem());
					
					  //  session.logoutUser();
//					   
				        Log.d("VendorHK:",VendorId);
				        Log.d("Crop:HK",CropId );
					int basecost=db.getbaseCost(Integer.parseInt(CropId));
					int qnt=db.getQuantity(Integer.parseInt(CropId));
					
					if(username.trim().length() > 0 && password.trim().length() > 0){
						
						
						if(Integer.parseInt(username)<basecost && Integer.parseInt(password)>qnt){
							alert.showAlertDialog(LoginActivity.this, "Bid failed..", "Please enter higher Bid Price than Basecost of crop and not higher quantity than available quantity.", false);
					
						}else if(Integer.parseInt(username)<basecost ){
					
							alert.showAlertDialog(LoginActivity.this, "Bid failed..", "Please enter higher Bid Price than Basecost of crop.", false);
						}	
						
						else if(Integer.parseInt(password)>qnt ){
							
							alert.showAlertDialog(LoginActivity.this, "Bid failed..", "You have entered higher quantity than available quantity.", false);
						}	
						else{

							CID=Integer.parseInt(CropId);
							VID=Integer.parseInt(VendorId);
							BIDCOST=Integer.parseInt(username);
							QNT=Integer.parseInt(password);
									
							AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
						    alt_bld.setMessage("Do you want to close this application ?")
						    .setCancelable(false)
						    .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
						    public void onClick(DialogInterface dialog, int id) {
						    	
						    	db.addToMasterBidtable(CID,VID,BIDCOST,pcost,QNT);
						    	
						    db.updateMastercroptable(CID, BIDCOST);
						    	
						    	Log.d("after",msg);

									AlertDialog.Builder alt_bld1 = new AlertDialog.Builder(LoginActivity.this);
								    alt_bld1.setMessage("Do you want to close this application ?")
								    .setCancelable(false)
								    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
								    public void onClick(DialogInterface dialog, int id) {
								    	db.sendSmsToFarmer(CID,VID,BIDCOST,QNT);
								    	Log.d("ab","1");
								    	Intent intent = new Intent(getApplicationContext(), Gsms.class);
								    	 intent.putExtra(EXTRA_MESSAGE1, Integer.toString(CID));
								 	    intent.putExtra(EXTRA_MESSAGE2,Integer.toString(VID));
								 	   intent.putExtra(EXTRA_MESSAGE3, Integer.toString(BIDCOST));
								 	    intent.putExtra(EXTRA_MESSAGE4,Integer.toString(QNT));
								    	Log.d("ab","2");
										startActivity(intent);
										Log.d("ab","3");
										
											finish();
											Log.d("ab","4");
								    	
								    }
								    });
								 
								    AlertDialog alert = alt_bld1.create();
								    // Title for AlertDialog
								    alert.setTitle("Congratulations!!!!!");
								    alert.setMessage("Your Bid has been recorded successfully." +
								    		"Thank you for using FarmerVendor Collaberation  application." +
								    		"You will be informed regarding Bid related Information.");
								    // Icon for AlertDialog
								    alert.setIcon(R.drawable.success);
								    alert.show();
								  
						    }
						    })
						    .setNegativeButton("Reject", new DialogInterface.OnClickListener() {
						    public void onClick(DialogInterface dialog, int id) {
						  
						    	  finish();
						}
						    });
						    AlertDialog alert = alt_bld.create();
						    // Title for AlertDialog
						    alert.setTitle("Terms And Conditions");
						    alert.setMessage("Every vendor must follow the Terms and conditions with respect to making bid on crops." +
						    		"Any Bid cannot be taken back by vendor." +
						    		"Bid is a legal agreement between vendor and farmer, after making bid if bid is suitable to farmer " +
						    		"vendor is bound to purchase." +
						    		"For more details go on tab HELP in homepage");
						    // Icon for AlertDialog
						    alert.setIcon(R.drawable.success);
						    alert.show();
							
						}
						
					}
					else if(username.trim().length() <= 0 && password.trim().length() <= 0){
						
						alert.showAlertDialog(LoginActivity.this, "Bid failed..", "Please enter Bid Price and Quantity for Bid.", false);
					}
					
					else if(username.trim().length() <= 0){
					
						alert.showAlertDialog(LoginActivity.this, "Bid failed..", "Please enter Bid Price.", false);
					}
					else if(password.trim().length() <= 0){
					
						alert.showAlertDialog(LoginActivity.this, "Bid failed..", "Please enter Quantity for Bid.", false);
					}
					
				}
			});
	       
	     Log.d("abmsg",msg);
	        //db.sendSmsToFarmer(CID,VID,BIDCOST,QNT);
	    }        
	}


